package com.chj.zhongji.class03;

import java.util.ArrayList;
import java.util.List;

// https://leetcode-cn.com/problems/diagonal-traverse/
public class Code02_ZigZagMatrix {
	public static int[] printMatrixZigZag(int[][] matrix) {

		if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
			return new int[] {};
		}

		List<Integer> path = new ArrayList<>();
		int tR = 0;
		int tC = 0;
		int dR = 0;
		int dC = 0;
		int endR = matrix.length - 1;
		int endC = matrix[0].length - 1;
		boolean fromUp = false;
		while (tR != endR + 1) {
			printLevel(path, matrix, tR, tC, dR, dC, fromUp);
			tR = tC == endC ? tR + 1 : tR;
			tC = tC == endC ? tC : tC + 1;
			dC = dR == endR ? dC + 1 : dC;
			dR = dR == endR ? dR : dR + 1;
			fromUp = !fromUp;
		}
		System.out.println(path);
		int[] res = new int[(endR + 1) * (endC + 1)];
		for (int i = 0; i < path.size(); i++) {
			res[i] = path.get(i);
		}

		return res;
	}

	public static void printLevel(List<Integer> path, int[][] m, int tR, int tC, int dR, int dC, boolean f) {
		if (f) {
			while (tR != dR + 1) {
				System.out.print(m[tR++][tC--] + " ");
				path.add(m[tR++][tC--]);
			}
		} else {
			while (dR != tR - 1) {
				System.out.print(m[dR--][dC++] + " ");
				path.add(m[dR--][dC++]);
			}
		}
	}

	public static void main(String[] args) {
		int[][] matrix = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } };
		printMatrixZigZag(matrix);
	}
}
